package com.linghang.wusthelper.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.linghang.wusthelper.annotation.LhAuthen;
import com.linghang.wusthelper.dao.primary.LhstudioDao;
import com.linghang.wusthelper.exception.AuthenException;
import com.linghang.wusthelper.exception.LhAuthenException;
import com.linghang.wusthelper.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author origin
 * 领航登录认证拦截器
 */
public class LhAuthenticationIntercaptor implements HandlerInterceptor {

    @Autowired
    private LhstudioDao lhstudioDao;

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        String token = request.getHeader("token");     //从请求头中获取token
        //  如果不是映射到方法直接跳过
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        //  检查是否有Lhauthen注解,没有则直接跳过
        if (method.isAnnotationPresent(LhAuthen.class)){
            LhAuthen lhAuthen = method.getAnnotation(LhAuthen.class);
            if (lhAuthen.required()){
                //  token为空则为非法请求
                if (token == null){
                    throw new LhAuthenException("系统权限认证失败");
                }
                String stuNum;
                //  从token中取出stuNum
                try{
                    stuNum = JWT.decode(token).getClaim("stuNum").asString();
                }catch (JWTDecodeException e){
                    throw new AuthenException("token无效");
                }
                int result = lhstudioDao.checkExist(stuNum);
                if (result == 0){
                    throw new LhAuthenException("此用户无权限");
                }
                //  验证token是否有效
                String secret = redisService.get(stuNum+":lhUUID");
                if (secret == null){
                    throw new AuthenException("token已过期");
                }
                Algorithm algorithm = Algorithm.HMAC256(secret);
                JWTVerifier jwtVerifier = JWT.require(algorithm)
                        .withIssuer("lhstudio")
                        .build();
                try{
                    jwtVerifier.verify(token);
                }catch (JWTVerificationException e){
                    return false;
                }
                return true;
            }
        }
        return true;
    }
}
